const handle_nx = (height, low) => {
  const range = Math.abs(height - low);
  return `${Math.ceil(range / 5)}x`;
};

/**
 * 通用阶梯卖出计算函数
 * @param {number} initialAmount - 初始总量 (默认1)
 * @param {number} percent - 当前涨幅百分比
 * @param {number} nx - 触发卖出的涨幅步长
 * @returns {number} - 总卖出量
 */
const calculate_sale = (initialAmount, percent, nx, name) => {
  const increasePercent = parseFloat(percent);
  const stepPercent = nx.slice(0, -1);

  // 核心计算逻辑
  const fullStages = Math.floor(increasePercent / stepPercent);
  const fraction = increasePercent % stepPercent;

  // 阶梯卖出后剩余量，每次剩0.75，就是0.75的n次方
  const remainingAfterFull = initialAmount * Math.pow(0.75, fullStages);
  // 完整阶梯卖出量计算
  const fullStageSold = initialAmount - remainingAfterFull;

  // 未满阶梯的线性卖出量
  const fractionalRatio = fraction / stepPercent;
  const fractionalSold = remainingAfterFull * 0.25 * fractionalRatio;
  if (name === "华安") {
    return (fullStageSold + fractionalSold).toFixed(4);
  } else {
    return Math.ceil(fullStageSold + fractionalSold);
  }
};

const result_formatter = (estimation, name, nx, result) => {
  return estimation > 0
    ? `${name}_${nx}: 卖出 ${result} 份`
    : `${name}_${nx}: 买入 ${result}`;
};

const handle_result = (obj) => {
  let {
    name,
    have,
    rest,
    high,
    low,
    estimation,
    current_difference,
    reality,
    total_difference,
    result,
  } = obj;
  const total = estimation > 0 ? have : rest;
  const current_estimation =
    parseFloat(estimation) + parseFloat(current_difference);
  const final_estimation = Math.abs(current_estimation);
  const nx = handle_nx(high, low);

  result = calculate_sale(total, final_estimation, nx, name);

  console.log(result_formatter(estimation, name, nx, result));
};

// 获取时间函数
const get_time = () => dayjs().format("YYYY-MM-DD");

// 处理Excel的主函数
async function handleXlsx(xlsxData = {}) {
  try {
    const sheetName = xlsxData.name;
    // const day = getTime();
    xlsxData.day = getTime();

    // 转换数据为有序数组（按Excel列顺序）
    const params = [
      xlsxData.day,
      xlsxData.name,
      xlsxData.have,
      xlsxData.rest,
      xlsxData.estimation,
      xlsxData.reality,
      xlsxData.current_difference,
      xlsxData.high,
      xlsxData.low,
      xlsxData.nx,
      xlsxData.result,
      xlsxData.total_difference,
    ];

    // 1. 初始化工作簿
    const workbook = new ExcelJS.Workbook();

    // 2. 读取现有文件（保留所有样式）
    await workbook.xlsx.readFile("./data.xlsx");

    // 3. 获取指定工作表
    const worksheet = workbook.getWorksheet(sheetName);
    if (!worksheet) throw new Error(`工作表 ${sheetName} 不存在`);

    // 4. 插入新行（在第二行插入，保留表头样式）
    const targetRow = 2; // 插入到第二行（原第一行下方）
    worksheet.insertRow(targetRow, params);

    // 5. 继承表头样式（假设表头在第一行）
    const headerRow = worksheet.getRow(1);
    const rowToStyle = worksheet.getRow(targetRow);

    // 6. 保存文件（保留原有样式）
    await workbook.xlsx.writeFile("./data.xlsx");
    console.log("文件更新成功，样式已保留");
  } catch (err) {
    console.error("处理Excel时发生错误:", err.message);
  }
}

module.exports = {
  handle_nx,
  calculate_sale,
  result_formatter,
  get_time,
  handle_result,
};
